package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.domain.StrategyComment;
import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.query.TravelCommentObjcet;
import cn.wolfcode.luowowo.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private MongoTemplate template;
    @Autowired
    private TravelCommentRepository travelCommentRepository;


    @Override
    public TravelComment get(String id) {
        return  travelCommentRepository.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> list() {
        return  travelCommentRepository.findAll();

    }



    @Override
    public Page<TravelComment> query(TravelCommentObjcet qo) {
        //创建查询对象
        Query query = new Query();
        //分页查询
        if(StringUtils.hasLength(qo.getTravelId())){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        //关键字查询

        PageRequest request = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        return DBHelper.query(template,TravelComment.class,query,request);
    }



    @Override
    public void delete(String id) {
        travelCommentRepository.deleteById(id);
    }

    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        travelComment.setCreateTime(new Date());
        travelCommentRepository.save(travelComment);
    }

    @Override
    public void commentAdd(TravelComment comment) {
        comment.setCreateTime(new Date());
        comment.setId(null);

        //评论的评论
        String refId = comment.getRefComment().getId();
        if (StringUtils.hasLength(refId)) {
            //设置引入评论
            TravelComment refComment = this.get(refId);
            comment.setRefComment(refComment);
        }
        travelCommentRepository.save(comment);

    }

    @Override
    public List<TravelComment> queryByTravelId(String travelId) {

        return travelCommentRepository.findByTravelIdOrderByCreateTimeDesc(travelId);
    }


}
